import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/services.dart';
import 'package:flutter_demo/core/common/values/server.dart';
import 'package:path_provider/path_provider.dart';

class FileUtils {
  static Future<String> assetFileToApplicationFile(
      String localDir, String fileName) async {
    var bytes = await rootBundle.load("assets/$localDir/$fileName");
    ByteBuffer buffer = bytes.buffer;
    String dir = (await findPath(localDir))!.path;
    String filePath = "$dir/$fileName";
    // if (await fileExists(dir, fileName)) {
    //   logger.i(dir + fileName);
    //   return filePath;
    // }
    await new File(filePath).writeAsBytes(
        buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
    return filePath;
  }

  static Future<Directory?> findPath(String path) async {
    String? externalStorageDirPath;
    if (Platform.isAndroid) {
      final directory = await getExternalStorageDirectory();
      externalStorageDirPath = directory?.path;
    } else if (Platform.isIOS) {
      externalStorageDirPath =
          (await getApplicationDocumentsDirectory()).absolute.path;
    }
    if (externalStorageDirPath == null) return null;
    externalStorageDirPath = "$externalStorageDirPath/$path";
    final savedDir = Directory(externalStorageDirPath);
    // 判断下载路径是否存在
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      // 不存在就新建路径
      savedDir.create();
    }
    return savedDir;
  }

  static Future<bool> fileExists(String subPath, String fileName) async {
    Directory? savedDir = await findPath(subPath);
    if (savedDir == null) return false;
    File file = File("${savedDir.path}/$fileName");

    bool exists = await file.exists();
    if (exists) {
      logger.i("文件大小${await file.length()}");
    }
    return exists;
  }
}
